package com.yidu.qianfeng.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yidu.qianfeng.common.bean.company.EmpInfo;
import com.yidu.qianfeng.common.bean.transport.TrackWaybill;
import com.yidu.qianfeng.common.bean.transport.TransportProtocol;
import com.yidu.qianfeng.common.bean.waybill.Waybill;
import com.yidu.qianfeng.common.bean.waybill.WaybillCondition;
import com.yidu.qianfeng.common.bean.waybill.WaybillWrap;
import com.yidu.qianfeng.common.util.JsonMsgUtil;
import com.yidu.qianfeng.common.util.LayuiJsonWrap;
import com.yidu.qianfeng.mapper.ChientMapper;
import com.yidu.qianfeng.mapper.SubstationMapper;
import com.yidu.qianfeng.mapper.TrackWaybillMapper;
import com.yidu.qianfeng.mapper.WaybillMapper;
import com.yidu.qianfeng.service.TrackWaybillService;
import com.yidu.qianfeng.service.WaybillService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * @Author: TangSheng
 * @Description: 运单业务实现类
 * @Date Created in 17:01 2021/3/16
 * @since 1.0
 */

@Service("waybillServiceImpl")
public class WaybillServiceImpl implements WaybillService {


    //注入跟踪业务service
    @Resource(name = "trackWaybillServiceImpl")
    private TrackWaybillService trackWaybillService;

    //注入运单数据映射Mapper
    @Resource(name = "waybillMapper")
    private WaybillMapper waybillMapper;

    //注入跟踪数据映射Mapper
    @Resource(name = "trackWaybillMapper")
    private TrackWaybillMapper trackWaybillMapper;

    //注入分站数据映射
    @Resource(name = "substationMapper")
    private SubstationMapper substationMapper;

    //注入客户数据映射
    @Resource(name = "chientMapper")
    private ChientMapper chientMapper;

    //注入财务api
    @Resource(name = "financeApi")
    private FinanceApi financeApi;

    /**
     *  新增运单
     * @param waybill 需要添加的新的运单的对象
     * @param loginEmpInfo 当前登录的员工
     * @return json格式返回消息
     */
    @Override
    @Transactional
    public String addNewWaybill(Waybill waybill, EmpInfo loginEmpInfo) {
        //查询运单根据运单号
        Waybill selectById = waybillMapper.selectById(waybill.getWaybillConsignNum());
        //判断运单号是否为空
        if (selectById != null){
            //为空返回失败消息，当前托运单号已存在，请重新输入托运单号！
            return JsonMsgUtil.createJsonMessage(0, "保存成功", "当前托运单号已存在，请重新输入托运单号！");
        }
        //新增运单并返回结果
        int insertResult = waybillMapper.insert(waybill);
        //生成跟踪记录，状态1
        trackWaybillService.generateTrackAccept(waybill,loginEmpInfo);
        //生成财务记录
        //收入
        financeApi.financeRecord(1,
                "营业收支",
                waybill.getWaybillIncomeTotal(),
                "运单现金现收",
                "运单号："+waybill.getWaybillConsignNum(),
                chientMapper.byIdQueryShipper(waybill.getWaybillShipperId()).getShipperCom(),
                waybill.getWaybillStartingSubst(),
                loginEmpInfo);
        //支出
        financeApi.financeRecord(0,
                "提货开支",
                waybill.getWaybillPickupSpend(),
                "运单提货现金",
                "运单号："+waybill.getWaybillConsignNum(),
                chientMapper.byIdQueryShipper(waybill.getWaybillShipperId()).getShipperCom(),
                waybill.getWaybillStartingSubst(),
                loginEmpInfo);
        //返回新增结果，消息："保存成功", "保存运单失败，请稍后再试。"
        return JsonMsgUtil.createJsonMessage(insertResult, "保存成功", "保存运单失败，请稍后再试。");
    }

    /**
     * 删除运单根据托运单号数组
     * @param waybillConsignNumS 运单托运单号数组
     * @return json格式返回消息
     */
    @Override
    @Transactional
    public String deleteWaybillByConsignNumS(String[] waybillConsignNumS) {
        //托运单号数组转换为List集合
        List<String> consignNumList = new ArrayList<>(Arrays.asList(waybillConsignNumS));

        //循环托运单号集合
        for (String waybillConsignNum : consignNumList) {
            //查询运单是否已装车发运
            QueryWrapper<TrackWaybill> trackWaybillQueryWrapper = new QueryWrapper<>();
            //跟踪类型为：2,3,4,5,6,7
            trackWaybillQueryWrapper.in("track_type", 2,3,4,5,6,7);
            //跟踪托运单号eq
            trackWaybillQueryWrapper.eq("track_consign_num", waybillConsignNum);
            //查询条目数
            int isNotCancel = trackWaybillMapper.selectCount(trackWaybillQueryWrapper);

            //结果小于等于零则可以删除运单
            if (isNotCancel <= 0){
                //删除对应的运单
                waybillMapper.deleteById(waybillConsignNum);

                //根据跟踪托运单号track_consign_num删除对应的跟踪记录
                QueryWrapper<TrackWaybill> trackQueryWrapper = new QueryWrapper<>();
                trackQueryWrapper.in("track_consign_num", consignNumList);
                trackWaybillMapper.delete(trackQueryWrapper);
            } else {
                //返回”已装车运输，不可作废。“的消息
                return JsonMsgUtil.createJsonMessage(0, "取消订单成功", "运单号"+waybillConsignNum+"已装车运输，不可作废。");
            }

        }
        //返回json消息，结果恒定为1，修改消息："取消订单成功", "取消订单失败，请稍后再试"
        return JsonMsgUtil.createJsonMessage(1, "取消订单成功", "取消订单失败，请稍后再试");

    }

    /**
     * 修改运单根据带主键的运单对象
     * @param waybill 带托运单号主键的运单对象
     * @return json格式返回消息
     */
    @Override
    public String updateWaybill(Waybill waybill) {
        //根据带运单号的运单实体修改运单信息
        int updateResult = waybillMapper.updateById(waybill);
        //返回修改消息："修改成功", "修改运单失败，请稍后再试。"
        return JsonMsgUtil.createJsonMessage(updateResult, "修改成功", "修改运单失败，请稍后再试。");
    }

    /**
     *  查询运单分页数据，layui格式
     * @param page 当前页
     * @param limit 显示条目数
     * @return layui格式当前页的数据
     */
    @Override
    public LayuiJsonWrap queryWaybillLimitLayui(int page, int limit) {
        //计算偏移量
        int offset = (page-1)*limit;
        //查询运单包装数据列表
        List<WaybillWrap> waybillWraps = waybillMapper.selectWaybillLimit(offset, limit);
        //返回包含总条目数,数据的、layui包装格式数据
        return new LayuiJsonWrap(waybillMapper.selectCount(null), waybillWraps);
    }

    /**
     *  根据条件查询运单，layui格式
     * @param condition 运单查询条件包装类
     * @return layui格式当前条件当前页数据
     */
    @Override
    public LayuiJsonWrap queryWaybillConditionLimitLayui(WaybillCondition condition) {
        //条件包装类计算偏移量
        condition.setOffset((condition.getPage()-1)*condition.getCount());
        //返回包含总条目数,数据的、layui包装格式数据
        return new LayuiJsonWrap(waybillMapper.selectWaybillCountByCondition(condition),waybillMapper.selectWaybillCondition(condition));
    }

    /**
     * 查询运单根据托运单号
     * @param waybillConsignNum 运单表的主键，托运单号
     * @return 运单
     */
    @Override
    public Waybill queryWaybillById(String waybillConsignNum) {
        //查询运单根据托运单号
        return waybillMapper.selectById(waybillConsignNum);
    }

    /**
     * 查询司机正在运输的运输单路线
     * @param carNumber 司机车号
     * @return 运输协议，只有出发站和到达地
     */
    @Override
    public TransportProtocol queryDriverNowRoute(String carNumber) {
        return waybillMapper.selectDriverNowTrans(carNumber);
    }
}
